package com.fancy.learncenter.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;

import com.alipay.sdk.app.EnvUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.LoginDataBean;
import com.fancy.learncenter.bean.PayDataBean;
import com.fancy.learncenter.bean.UpHeaderBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.SPUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import fancy.hyypaysdk.pay.PayCallBack;
import fancy.hyypaysdk.pay.alipay.AliPayUtils;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class SettingHeaderActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {

    @Bind(R.id.headerIcon)
    SimpleDraweeView headerIcon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_header, Status.STATUS, "个人头像");
        ButterKnife.bind(this);
        getTakePhoto().onCreate(savedInstanceState);

        setRight("保存", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(urlPath)) {
                    upHeaderData(urlPath);
                } else {
                    ToastUtil.show("请先选择照片");
                }


            }
        });
    }

    String urlPath;

    @OnClick({R.id.cammera, R.id.ablum})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ablum:
                File file = new File(Environment.getExternalStorageDirectory(), Constant.HEADER_CUT_PATH + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                Uri imageUri = Uri.fromFile(file);
                getTakePhoto().onPickFromGalleryWithCrop(imageUri, getCropOptions());
                break;
            case R.id.cammera:
                File file2 = new File(Environment.getExternalStorageDirectory(), Constant.HEADER_CUT_PATH + System.currentTimeMillis() + ".jpg");
                if (!file2.getParentFile().exists()) file2.getParentFile().mkdirs();
                Uri imageUri2 = Uri.fromFile(file2);
                getTakePhoto().onPickFromCaptureWithCrop(imageUri2, getCropOptions());
                break;
        }
    }

    private TakePhoto takePhoto;
    private InvokeParam invokeParam;

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        headerIcon.setImageURI("file://" + result.getImage().getOriginalPath());
        urlPath = result.getImage().getOriginalPath();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        urlPath = "";
    }

    @Override
    public void takeCancel() {
        urlPath = "";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }


    private CropOptions getCropOptions() {
        int height = 400;
        int width = 400;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setWithOwnCrop(true);
        return builder.create();
    }


    private void upHeaderData(String urlPath) {
        HttpMehtod.getInstance().upHeaderIcon(urlPath, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<UpHeaderBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), UpHeaderBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(),baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<UpHeaderBean>() {
                    @Override
                    public void success(UpHeaderBean dataBean) {
                        LoginUserSharePrefernce.putHeaderPath(dataBean.getImgUrl());
                        LoginUserSharePrefernce.update(true);
                        ToastUtil.show("头像上传成功");
//                        finish();
                    }

                    @Override
                    public void fail(String errorCode) {

                    }


                }).dealData();
            }
        });
    }

}
